//
//  PLDirectoryBrowserController.m
//  Plankton
//
//  Created by Marc Schlichte on 2008-07-18.
//  Copyright 2008 Framework Labs. All rights reserved.
//

#import "PLDirectoryBrowserController.h"

#import "PLPlatform.h"


@interface PLDirectoryBrowserController ()

@property(retain) NSMutableSet *outstandingServices;

- (void)doUpdate;
- (void)scheduleNextSearchOrFinish;

@end


@implementation PLDirectoryBrowserController

@synthesize updating;
@synthesize outstandingServices;

- (id)init
{
    if (self = [super init]) {
        platform = [[PLPlatform alloc] init];
        directory = [[PLDirectory alloc] initWithPlatform:platform];
        directory.delegate = self;
        directory.discoverable = YES;
        directory.autoDiscover = YES;
        directory.receivePushUpdates = YES;
        entries = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [outstandingServices release];
    [entries release];
    [directory release];
    [platform release];
    [super dealloc];
}

- (IBAction)update:(id)sender
{
    [self doUpdate];
}

#pragma mark category methods

- (void)doUpdate
{
    if (updating) {
        return;
    }
    [entries removeAllObjects];
    self.updating = YES;
    
    [directory searchServices];
}

- (void)scheduleNextSearchOrFinish
{
    if ([outstandingServices count] == 0) {
        [self willChangeValueForKey:@"entries"];
        [self didChangeValueForKey:@"entries"];
        
        self.updating = NO;
    }
    else {
        NSString *service = [outstandingServices anyObject];
        [outstandingServices removeObject:service];
        
        [directory searchAidsForService:service];
    }
}


#pragma mark directory delegate methods

- (void)directory:(PLDirectory *)directory foundAid:(NSString *)aid forService:(NSString *)service
{
    [entries addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                        service, @"service",
                        aid, @"aid", nil]];
}

- (void)directory:(PLDirectory *)directory searchDoneForService:(NSString *)service
{
    [self scheduleNextSearchOrFinish];
}

- (void)directory:(PLDirectory *)directory foundServices:(NSSet *)services
{
    self.outstandingServices = [services mutableCopy];
    [self scheduleNextSearchOrFinish];
}

- (void)directoryChangedPeerSet:(PLDirectory *)directory
{
    [self doUpdate];
}

- (void)directory:(PLDirectory *)directory addedAid:(NSString *)aid forService:(NSString *)service
{
    // todo: just patch the entries list instead!
    [self doUpdate];
}

- (void)directory:(PLDirectory *)directory removedAid:(NSString *)aid forService:(NSString *)service
{
    // todo: just patch the entries list instead!
    [self doUpdate];
}

@end
